package edu.wuster.blog.utils;

/*
 *
 * 阿里云OSS工具类
 * 文件上传工具*/


import com.aliyun.oss.OSS;
import com.aliyun.oss.common.auth.*;
import com.aliyun.oss.OSSClientBuilder;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;
import java.io.InputStream;
import java.util.UUID;


@Component
public class AliOSSUtils {

    //文件上传方法
    public String upload(MultipartFile file) throws Exception {

        //endpoint 华东1杭州
        String endpoint = "https://oss-cn-hangzhou.aliyuncs.com";

        //bucketname
        String bucketName = "blog-image-wuster";

        //从环境变量中获取访问凭证
        EnvironmentVariableCredentialsProvider credentialsProvider = CredentialsProviderFactory.newEnvironmentVariableCredentialsProvider();

        //获取文件的输入流
        InputStream inputStream = file.getInputStream();

        //避免文件覆盖
        String originalFilename = file.getOriginalFilename();
        String newFilename = UUID.randomUUID() + originalFilename.substring(originalFilename.lastIndexOf('.'));

        //创建OSSClient实例
        OSS ossClient = new OSSClientBuilder().build(endpoint, credentialsProvider);
        //上传文件到阿里云OSS
        ossClient.putObject(bucketName, newFilename, inputStream);

        //获取文件访问路径(拼接路径)
        String url = endpoint.split("//")[0] + "//" + bucketName + "." + endpoint.split("//")[1] + "/" + newFilename;

        //关闭云服务器
        ossClient.shutdown();

        //返回路径
        return url;
    }

}
